<template>
  <div class="px-10px" v-if="props.wid">
    <div class="flex justify-end flex-items-center m-b-20px">
      <!--      <div v-if="current.level === 1">-->
      <el-button v-if="gradientAddVisible" @click="handleItemAdd">新增</el-button>
      <el-button v-if="gradientDeleteVisible" type="danger" @click="handleItemDelete">
        删除
      </el-button>
      <!--      </div>-->
    </div>
    <div v-for="(current, currentIndex) in form.product_prices" :key="current.level">
      <el-card shadow="never">
        <!--        <div class="m-b-20px font-bold">{{ `梯度 ${current.level}` }}</div>-->
        <el-form :model="current" :rules="rules" ref="formRef">
          <el-form-item label="币种" prop="currency_id">
            <el-select
              v-model="current.currency_id"
              placeholder="请选择币种"
              :clearable="false"
              style="width: 100%"
              @change="handleChangeCurrency"
            >
              <el-option
                v-for="item in currencyList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="价格" prop="price">
            <el-input
              v-model="current.price"
              placeholder="请输入"
              @input="
                (e) => {
                  current.price = e
                    .replace(/[^\d.]/g, '')
                    .replace(/\.{2,}/g, '.')
                    .replace('.', '$#$')
                    .replace(/\./g, '')
                    .replace('$#$', '.')
                    .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
                    .replace(/^\./g, '')
                  // 自动计算折扣价格
                  if (current.discount && current.discount.length) {
                    current.discount.forEach((item) => {
                      if (item.num && current.price) {
                        item.sales_price = parseFloat(current.price)
                      }
                    })
                  }
                }
              "
              style="width: 100%"
            />
          </el-form-item>
          <div v-if="current.discount && current.discount.length">
            <div
              v-for="(currentGradient, currentGradientIndex) in current.discount"
              :key="currentGradient.level"
            >
              <el-row :gutter="24" align="middle">
                <el-col :span="isMobile ? 24 : 7">
                  <el-form-item
                    :label="`数量 ${currentGradient.level}`"
                    :prop="'discount.' + currentGradientIndex + '.num'"
                    :rules="ruleFn('num', current.discount, currentGradientIndex)"
                  >
                    <el-input-number
                      v-model="currentGradient.num"
                      :min="1"
                      :precision="0"
                      placeholder="请输入"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <!--                <el-col :span="7">-->
                <!--                  <el-form-item-->
                <!--                    :label="`折扣率 ${currentGradient.level} (%)`"-->
                <!--                    :prop="'discount.' + currentGradientIndex + '.rate'"-->
                <!--                    :rules="ruleFn('rate', current.discount, currentGradientIndex)"-->
                <!--                  >-->
                <!--                    <el-input-number-->
                <!--                      v-model="currentGradient.rate"-->
                <!--                      :min="1"-->
                <!--                      :max="100"-->
                <!--                      placeholder="请输入"-->
                <!--                      style="width: 100%"-->
                <!--                      @blur="handleCalcSalePrice(currentIndex, currentGradientIndex)"-->
                <!--                      @change="handleCalcSalePrice(currentIndex, currentGradientIndex)"-->
                <!--                    />-->
                <!--                  </el-form-item>-->
                <!--                </el-col>-->
                <el-col :span="isMobile ? 24 : 7">
                  <el-form-item
                    :label="`折扣价格 ${currentGradient.level}`"
                    :prop="'discount.' + currentGradientIndex + '.sales_price'"
                    :rules="ruleFn('sales_price', current.discount, currentGradientIndex)"
                  >
                    <el-input-number
                      v-model="currentGradient.sales_price"
                      :precision="2"
                      placeholder="请输入"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="isMobile ? 24 : 3" v-if="currentGradient.level === 1">
                  <el-form-item label="">
                    <el-button @click="handleGradientAdd(currentIndex, current)">新增</el-button>
                    <el-button @click="handleGradientDelete(currentIndex, current)">删除</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>
<script setup lang="ts">
import Decimal from 'decimal.js'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { getCurrencyApi } from '@/api/inventory'

// 移动端检测
import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()
const isMobile = computed(() => appStore.getMobile)
const { query } = useRoute()

const formRef = ref<Array<FormInstance> | null>(null)

const props = defineProps({
  wid: {
    type: String,
    default: () => null
  }
})

const form = ref<Record<string, Array<Record<string, any>>>>({
  product_prices: [
    {
      level: 1,
      currency_id: '',
      price: '',
      discount: [
        {
          level: 1,
          num: void 0,
          rate: void 0,
          sales_price: void 0
        }
      ]
    }
  ]
})

const rules = ref<FormRules>({
  currency_id: [{ required: true, message: '请选择币种', trigger: 'change' }],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: Function) => {
        if (!value || Number(value) <= 0) {
          callback(new Error('价格必须大于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  first_leg_logistics_fee: [
    {
      validator: (rule: any, value: any, callback: Function) => {
        // 空值或大于0都通过，只有0或负数才报错
        if (value && Number(value) <= 0) {
          callback(new Error('头程物流费必须大于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

const gradientAddVisible = computed(
  () => !(form.value.product_prices.length === currencyList.value.length)
)
const gradientDeleteVisible = computed(() => form.value.product_prices.length >= 1)

const currencyList = ref<Array<Record<string, any>>>([])

//动态处理阶梯数量、折扣率、折扣价表单校验
const ruleFn = (
  key: string,
  currentGradientRow: Record<string, any>,
  currentGradientIndex: number
) => {
  const currentGradientRules = {
    num: () => ({
      required: true,
      trigger: ['blur', 'change'],
      validator: (_: FormRules, value: string, callback: Function) => {
        if (!value) {
          callback(new Error('请输入数量'))
        } else {
          if (
            currentGradientIndex &&
            parseFloat(value) <= currentGradientRow[currentGradientIndex - 1].num
          ) {
            callback(
              new Error(
                `数量${currentGradientRow[currentGradientIndex].level}数量不能小于或等于上一级数量`
              )
            )
          } else {
            callback()
          }
        }
      }
    }),
    rate: () => ({
      required: true,
      trigger: ['blur', 'change'],
      validator: (_: FormRules, value: string, callback: Function) => {
        if (!value) {
          callback(new Error('请输入折扣率'))
        } else {
          if (
            currentGradientIndex &&
            parseFloat(value) >= currentGradientRow[currentGradientIndex - 1].rate
          ) {
            callback(
              new Error(
                `折扣率${currentGradientRow[currentGradientIndex].level}(%)不能大于或等于上一级折扣率`
              )
            )
          } else {
            callback()
          }
        }
      }
    }),
    sales_price: () => ({
      required: true,
      trigger: ['blur', 'change'],
      validator: (_: FormRules, value: string, callback: Function) => {
        if (!value) {
          callback(new Error('请输入折扣价格'))
        } else {
          callback()
        }
      }
    })
  }
  return currentGradientRules[key]()
}

//所有梯度币种选中集合
const markedCurrency = ref<Array<number>>([])

//动态处理币种下拉框禁选项
const handleChangeCurrency = (e: number) => {
  currencyList.value.forEach((item: Record<string, any>) => {
    if (item.value === e) {
      item.disabled = true
      if (!markedCurrency.value.includes(e)) {
        markedCurrency.value.push(e)
        const checkedIds = form.value.product_prices.flatMap((item: Record<string, any>) =>
          item.currency_id ? [item.currency_id] : []
        )
        currencyList.value.forEach((item: Record<string, any>) => {
          if (
            markedCurrency.value
              .filter((item: number) => !checkedIds.includes(item))
              .includes(item.value)
          ) {
            item.disabled = false
          }
        })
        markedCurrency.value = checkedIds
      }
    }
  })
}

//梯度折扣率发生变化计算折扣价格
const handleCalcSalePrice = (currentIndex: number, currentGradientIndex: number) => {
  if (!form.value.product_prices[currentIndex].price) {
    form.value.product_prices[currentIndex].discount[currentGradientIndex].rate = void 0
    return ElMessage.error('请先编辑价格')
  } else {
    if (form.value.product_prices[currentIndex].discount[currentGradientIndex].rate) {
      form.value.product_prices[currentIndex].discount[currentGradientIndex].sales_price =
        (parseFloat(
          new Decimal(form.value.product_prices[currentIndex].price!)
            .mul(
              new Decimal(
                form.value.product_prices[currentIndex].discount[currentGradientIndex].rate!
              )
            )
            .div(new Decimal(100))
            .toFixed(2)
        ) || 0) as any
    }
  }
}

//新增梯度板块
const handleItemAdd = () => {
  if (!props.wid) return ElMessage.error('请先选择仓库!')

  form.value.product_prices.push({
    level: form.value.product_prices.length + 1,
    currency_id: '',
    price: '',
    discount: [
      {
        level: 1,
        num: 100,
        rate: void 0,
        sales_price: void 0
      }
    ]
  })
}

//删除梯度板块
const handleItemDelete = () => {
  if (form.value.product_prices.length === 1) return ElMessage.error('就剩一个了，不能删除了')
  if (form.value.product_prices[form.value.product_prices.length - 1].currency_id) {
    currencyList.value.forEach((item: Record<string, any>) => {
      if (
        item.value === form.value.product_prices[form.value.product_prices.length - 1].currency_id
      )
        item.disabled = false
    })
  }
  form.value.product_prices.pop()
  markedCurrency.value = form.value.product_prices.flatMap((item: Record<string, any>) =>
    item.currency_id ? [item.currency_id] : []
  )
}

//新增梯度
const handleGradientAdd = (parentIndex: number, currentRow: Record<string, any>) => {
  if (currentRow.discount.length === 5) return ElMessage.error('已经有5个了，不能再加了')
  form.value.product_prices[parentIndex].discount.push({
    level: currentRow.discount.length + 1,
    num: 100,
    rate: void 0,
    sales_price: void 0
  })
}

//删除梯度
const handleGradientDelete = (parentIndex: number, currentRow: Record<string, any>) => {
  if (currentRow.discount.length === 1) return ElMessage.error('就剩一个了，不能删除了')
  form.value.product_prices[parentIndex].discount.pop()
}

//提交梯度数据
const gradientSubmit = async () => {
  const formElRuleResultList = await Promise.all(
    formRef.value!.map(async (item) => await item.validate((valid) => valid))
  )
  if (!formElRuleResultList.every((item) => item)) return Promise.reject('梯度表单校验不通过')
  return Promise.resolve(form.value)
}

//币种查询
const queryDropDownBox = async () => {
  if (!props.wid) return
  const resp = await getCurrencyApi(props.wid as string)
  currencyList.value = resp.data.list
  form.value.product_prices = [
    {
      level: 1,
      currency_id: currencyList.value.some((item) => item.value === 214) ? 214 : '',
      price: '',
      discount: [
        {
          level: 1,
          num: 100,
          rate: void 0,
          sales_price: void 0
        }
      ]
    }
  ]
  if (currencyList.value.some((item) => item.value === 214)) handleChangeCurrency(214)
}

onMounted(() => {
  queryDropDownBox()
})

defineExpose({
  queryDropDownBox,
  gradientSubmit
})
</script>
<style lang="less" scoped>
:deep(.el-form-item) {
  width: 100%;
}
</style>
